<!--
 * @Description: 
 * @Date: 2024-07-08 09:20:03
 * @LastEditTime: 2024-07-23 18:22:48
-->
<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="相册名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入相册名称" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { FormRules } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import * as albumphoto from '@/api/spb/partyWorkAlbum/index'
const userStore = useUserStore()
const message = useMessage()
const { t } = useI18n()
const emit = defineEmits(['success'])
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('新增相册') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = reactive({
  id: '',
  name: ''
})
const formRules = reactive<FormRules>({
  name: [{ required: true, message: '相册名称不能为空', trigger: 'blur' }]
})
const formRef = ref()
/**
 * @description:打开弹窗
 * @param {*} title 标题
 * @param {*} id id
 * @return {*}
 */
const open = async (title, id) => {
  dialogTitle.value = title
  resetForm()
  dialogVisible.value = true
  if (id) {
    formLoading.value = true
    formData.id = id
    try {
      const data = await albumphoto.getAlbum(id)
      Object.assign(formData, data)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
/**
 * @description: 表单提交
 * @return {*}
 */
const submitForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    if (dialogTitle.value === '新增相册') {
      await albumphoto.createAlbum({
        ...toRaw(formData),
        id: undefined
      })
      message.success(t('common.createSuccess'))
    } else {
      await albumphoto.updateAlbum({
        ...toRaw(formData)
      })
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    //发送操作成功的事件
    emit('success', true)
  } finally {
    formLoading.value = false
  }
}
/** 重置表单 */
const resetForm = () => {
  formData.id = ''
  formData.name = ''

  formRef.value?.resetFields()
}
</script>
<style lang="scss" scoped></style>
